package com.zut.controller.common;

import com.zut.utils.AliOssUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author 张晨
 * @date 2024/9/11 16:19
 * @desc
 */
@WebServlet("/upload")
public class UploadImage extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收图片
        //2.上传图片
        //2.1上传图片到数据库，会造成数据库压力过大
        //2.2把图片存在服务器所在电脑的磁盘上，图片过多会造成磁盘溢出
        //2.3搭建文件管理系统，minio fastdfs
        //2.4使用云服务器，(阿里云，腾讯云，华为云，网易云)OSS;
        //响应图片到前端
        //    图片上传三要素   post    file      enctype="multipart/form-data"(getParameter()方法失效)

        // req.getInputStream()  太繁琐，，会读取全部的文件

        //用第三方fileupload
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        //临时文件存储位置   不指定就会出现在默认位置(上传完自动销毁，可以不指定)
        // diskFileItemFactory.setRepository(new File("D:\\upload"));
        //临时文件大小
        // diskFileItemFactory.setSizeThreshold(1024 * 1024);
        //文件上传对象，该对象可以读取request中传过来的信息，封装成多个FileItem对象

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);

            for (FileItem fileItem : fileItems) {
                //判断是否是文件
                if (!fileItem.isFormField()) {
                    //是文件
                    //获取文件名
                    String fileName = fileItem.getName();
                    // System.out.println(fileName);
                    //获取文件流
                    InputStream inputStream = fileItem.getInputStream();
                    // System.out.println(inputStream);
                    //上传文件到服务器
                    String upload = AliOssUtil.upload(inputStream, fileName);
                    //把文件上传到服务器
                    resp.getWriter().write(upload);
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        }


    }
}
